import { stringify } from 'querystring';
import { history } from 'umi';
import { accountLogin, getCaptcha } from '@/services/login';
import { setAuthority } from '@/utils/authority';
import { getPageQuery, transAuthority, handleReturnMD5 } from '@/utils/utils';
import { message } from 'antd';

const Model = {
  namespace: 'login',
  state: {
    status: undefined,
    captchaUrl: '',
    currentUser: {},
  },
  effects: {
    *login({ payload }, { call, put }) {
      delete payload.type;
      delete payload.autoLogin;
      payload.password = handleReturnMD5(payload.password);
      const response = yield call(accountLogin, {
        ...payload,
        codeUuid: sessionStorage.getItem('uuid'),
      });

      if (response && response.code !== 0) {
        message.error(response.message);
      }

      if (response && response.message === 'success') {

        const urlParams = new URL(window.location.href);
        const params = getPageQuery();
        const {
          data: { token, name, roleName, isFirst, areaId, buttonList, resourceList },
        } = response;
        transAuthority(resourceList);
        sessionStorage.setItem('menuData', JSON.stringify(resourceList));
        const userInfo = {
          name,
          roleName,
          isFirst,
          areaId,
          buttonList,
        };
        sessionStorage.setItem('isFirst', isFirst);
        sessionStorage.setItem('userInfo', JSON.stringify(userInfo));
        const authorityObj = {
          currentAuthority: buttonList,
        };

        Object.assign(response, authorityObj);
        yield put({
          type: 'changeLoginStatus',
          payload: response,
        }); // Login successfully
        message.success('🎉 🎉 🎉  登录成功！');
        sessionStorage.setItem('token', token);
        let { redirect } = params;
        // if (redirect) {
        //   const redirectUrlParams = new URL(redirect);

        //   if (redirectUrlParams.origin === urlParams.origin) {
        //     redirect = redirect.substr(urlParams.origin.length);

        //     if (redirect.match(/^\/.*#/)) {
        //       redirect = redirect.substr(redirect.indexOf('#') + 1);
        //     }
        //   } else {
        //     window.location.href = '/';
        //     return;
        //   }
        // }
        // history.replace(redirect || '/');

        if (redirect) {
          //window.location.href = '/admin';
        }
        //history.replace('/');
        history.push('/');
      }
    },
    *captcha({ payload }, { call, put }) {
      const response = yield call(getCaptcha, payload);
      yield put({
        type: 'changeCaptcha',
        payload: URL.createObjectURL(response.data),
      });
    },
    *fetchCurrent(payload, { call, put }) {
      yield put({
        type: 'saveCurrentUser',
        payload: JSON.parse(sessionStorage.getItem('userInfo')),
      });
    },
    logout() {
      const { redirect } = getPageQuery(); // Note: There may be security issues, please note
      if (window.location.pathname !== '/user/login' && !redirect) {
        history.replace({
          pathname: '/user/login',
          search: stringify({
            redirect: window.location.href,
          }),
        });
      }
    },
  },
  reducers: {
    changeLoginStatus(state, { payload }) {
      setAuthority(payload.currentAuthority);
      return {
        ...state,
        status: payload.status,
        type: payload.type,
      };
    },
    changeCaptcha(state, { payload }) {
      return {
        ...state,
        captchaUrl: payload,
      };
    },
    saveCurrentUser(state, action) {
      return {
        ...state,
        currentUser: action.payload || {},
      };
    },
  },
};
export default Model;
